package com.ipbd.controller;

import com.ipbd.domain.AppUser;
import com.ipbd.service.AppUserService;
import com.ipbd.service.BreathRecordService;
import com.ipbd.service.FirstActionService;
import com.ipbd.service.QuestionnaireService;
import com.ipbd.utils.R;
import com.ipbd.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/home")
@Slf4j
public class CompleteRecordController {

    @Autowired
    private QuestionnaireService questionnaireService;

    @Autowired
    private FirstActionService firstActionService;

    @Autowired
    private AppUserService appUserService;

    @Autowired
    private BreathRecordService breathRecordService;

    /**
     * 修改用户状态
     * @return
     */
    @GetMapping("/status")
    public R updateUserStatus() {
        Integer id = UserHolder.getUser().getId();
        // 1.获取用户
        AppUser user = appUserService.query().eq("id", id).one();
        // 2.判断用户是否存在
        if (user == null) {
            return R.error("账号不存在，请先进行注册");
        }
        // 3.判断用户是否完成了基础任务（问卷测评 and 首次行为疗法）
        Long count1 = questionnaireService.query().eq("user_id", id).count();
        Long count2 = firstActionService.query().eq("user_id", id).count();
        // 4.判断是否完成了问卷测评
        if (count1 > 0) {
            user.setQuestionnaireStatus(0);
        }else {
            user.setQuestionnaireStatus(1);
        }
        // 5.判断是否完成了首次行为疗法
        if (count2 > 0) {
            user.setActionStatus(0);
        }else {
            user.setActionStatus(1);
        }
        appUserService.update(user, null);
        return R.ok()
                .put("questionnaireStatus", user.getQuestionnaireStatus())
                .put("actionStatus", user.getActionStatus());
    }

    /**
     * 获取呼吸训练次数
     * @return
     */
    @GetMapping("/breathCount")
    public R updateBreathCount() {
        return breathRecordService.getBreathCount();
    }
}
